/*=============================================================================
// File Name: 
// Author:  Wood.Wang
// Date:
// Message:
// Copyright 2012,All right is reserved;
=============================================================================*/
/* Includes -----------------------------------------------------------------*/
#include "drv_bm1383aglv.h"

#define     I2C_NUM     0

uint8_t BM1383AGLV_Init(void)
{
    unsigned char reg;

    reg = I2C_ReadByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_ID2);
    if(reg != BM1383AGLV_ID2_VAL)
    {
        return 1;
    }

    I2C_WriteByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_POWER_DOWN, BM1383AGLV_POWER_DOWN_VAL);
    delay_ms(WAIT_BETWEEN_POWER_DOWN_AND_RESET);
    I2C_WriteByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_RESET, BM1383AGLV_RESET_VAL);
        
    I2C_WriteByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_MODE_CONTROL, BM1383AGLV_MODE_CONTROL_VAL);
    delay_ms(WAIT_TMT_MAX);

    return 0;
}

void BM1383AGLV_get_rawdata(unsigned char *buff)
{
    I2C_PageRead(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS,
                BM1383AGLV_PRESSURE_MSB,
                buff, GET_BYTE_PRESS_TEMP);

}

void BM1383AGLV_get_val(float *press, float *temp)
{

  unsigned char val[GET_BYTE_PRESS_TEMP];
  unsigned long rawpress;
  short rawtemp;

  BM1383AGLV_get_rawdata(val);

  rawpress = (((unsigned long)val[0] << 16) | ((unsigned long)val[1] << 8) | (val[2]&0xFC)) >> 2;

  if (rawpress == 0) {
    return ;
  }

  *press = (float)rawpress / HPA_PER_COUNT;

  rawtemp = ((short)val[3] << 8) | val[4];

  if (rawtemp == 0) {
    return ;
  }

  *temp = (float)rawtemp / DEGREES_CELSIUS_PER_COUNT;

}

void BM1383AGLV_power_down(void)
{
    I2C_WriteByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_RESET, 0);
    I2C_WriteByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_POWER_DOWN, 0);
}

uint8_t BM1383AGLV_read_status(void)
{
    return I2C_ReadByte(I2C_NUM, BM1383AGLV_DEVICE_ADDRESS, BM1383AGLV_STATUS);
}


#if UART_SHELL == NR_MICRO_SHELL
#include "nr_micro_shell.h"

void bm1383aglv_read(char argc, char *argv)
{
    float   pressure,temperature;
    
    printf("BM1383AGLV:%02X\r\n",BM1383AGLV_Init());
    BM1383AGLV_get_val(&pressure,&temperature);
    printf("pressure=%f \t temperature=%f \r\n",pressure,temperature);
}

NR_SHELL_CMD_EXPORT(bm1383,   bm1383aglv_read,     "get pressure senser BM1383 data");

#endif


